package com.bdbit.ChargingStation.wx;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 微信相关配置
 */
@Slf4j
public class WxConfig {
    public static final String appid = "wx0dcb1b9df12a70fa";
    public static final String appSecret = "2cee375e8e4bfb337f5d45028d09290e";
    // 商户号
    public static final String merchantId = "1715399246";
    // 证书序列号
    public static final String certSerialNo = "5BE920D1E526D1267B78668708B2146C7EB4B0AC";
    public static final String apiV3key = "XCO1dQhdufwiBk5AHnVP9G5wpseTMg1w";
    public static final String privateKeyPath = "wxpay/apiclient_key.pem";
    public static String privateKey;



    public static Config getConfig() throws IOException {
        try {
            // 1. 优先使用已加载的私钥232
            String privateKeyContent = privateKey;
            if (privateKeyContent == null || privateKeyContent.isEmpty()) {
                // 2. 如果没有预加载，则读取文件
                privateKeyContent = readPrivateKeyFile();
            }
            log.info("成功加载私钥文件，长度: {}", privateKeyContent.length());

            // 3. 创建配置
            return new RSAAutoCertificateConfig.Builder()
                    .merchantId(merchantId)
                    .privateKey(privateKeyContent)
                    .merchantSerialNumber(certSerialNo)
                    .apiV3Key(apiV3key)
                    .build();
        } catch (Exception e) {
            log.error("创建微信支付配置失败", e);
            throw new IOException("无法创建微信支付配置", e);
        }
    }
    /**
     * 读取私钥文件内容
     */
    private static String readPrivateKeyFile() throws IOException {
        try {
            ClassPathResource resource = new ClassPathResource(privateKeyPath);
            if (!resource.exists()) {
                log.error("私钥文件不存在: {}", privateKeyPath);
                throw new FileNotFoundException("私钥文件未找到: " + privateKeyPath);
            }

            try (InputStream inputStream = resource.getInputStream()) {
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }
                String content = result.toString(StandardCharsets.UTF_8.name());
                log.info("成功读取私钥文件: {}, 长度: {}", privateKeyPath, content.length());
                return content;
            }
        } catch (IOException e) {
            log.error("读取私钥文件失败: {}", privateKeyPath, e);
            // 尝试备用方案：使用绝对路径或其他方式
            throw e;
        }
    }

    public static String readCertContent(String certName) throws IOException {
        ClassPathResource resource = new ClassPathResource(certName);
        if (resource.exists()) {
            try (InputStream inputStream = resource.getInputStream()) {
                // 使用Java 8兼容方式读取
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }
                return result.toString(StandardCharsets.UTF_8.name());
            }
        } else {
            System.out.println(certName + ": 证书文件未找到");
            return "";
        }
    }

    /**
     * 清理私钥格式
     */
    private static String cleanPrivateKey(String privateKey) {
        // 1. 确保有BEGIN/END标签
        if (!privateKey.contains("-----BEGIN PRIVATE KEY-----")) {
            log.warn("私钥缺少BEGIN PRIVATE KEY标签，尝试添加");
            privateKey = "-----BEGIN PRIVATE KEY-----" + privateKey;
        }
        if (!privateKey.contains("-----END PRIVATE KEY-----")) {
            log.warn("私钥缺少END PRIVATE KEY标签，尝试添加");
            privateKey = privateKey + "-----END PRIVATE KEY-----";
        }

        // 2. 移除标签之间的换行符
        String cleaned = privateKey
                .replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\\s", ""); // 移除所有空白字符

        // 3. 重新添加标签（无换行）
        return "-----BEGIN PRIVATE KEY-----" + cleaned + "-----END PRIVATE KEY-----";
    }
}
